//
//  KLCommentGoodViewController.m
//  KunLun
//
//  Created by Mac on 2018/1/17.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "KLCommentGoodViewController.h"
#import "KLCommentCollectionViewCell.h"
@interface KLCommentGoodViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property(nonatomic, strong) UICollectionView                     *collectionView;
@end

@implementation KLCommentGoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSInteger count = self.model.goodsorder.count;
    if (self.model.goodsorder.count != 1){
         [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"当前订单一共有%ld个商品，请依次评价",count]];
    }
   
    [self updateTitle];
    
    //collectionView
    UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
    flow.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    flow.minimumLineSpacing = 0;
    flow.minimumInteritemSpacing = 0;
    self.collectionView = [[UICollectionView alloc] initWithFrame:UIScreenFrame collectionViewLayout:flow];
    self.collectionView.backgroundColor = KL_backgroundColor;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[KLCommentCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    self.collectionView.scrollEnabled = NO;
    self.collectionView.pagingEnabled = YES;
    [self.view addSubview:self.collectionView];
    
    // Do any additional setup after loading the view.
}
- (void)configLeftItem{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(back)  forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"icon_返回"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"icon_返回"] forState:UIControlStateHighlighted];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    btn.frame = CGRectMake(0, 0, 44, 44);
    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:btn];
}

#pragma --mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.model.goodsorder.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(SCREEN_WIDTH/1, [KLUtils tabBarTop] - [KLUtils navgationBarBootom] + 49);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KLCommentCollectionViewCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    item.model = self.model.goodsorder[indexPath.row];
    __weak typeof(self) weakSelf =  self;
    __weak typeof(item) weakItem =  item;
    [item setGoodAction:^(NSString *goodId) {
        [weakSelf onSelectedGoodWithIndexPath:indexPath cell:weakItem];
    }];
    [item.commentButton  setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedCommitWithIndexPath:indexPath cell:weakItem];
    }];
    return item;
}
#pragma --mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}

#pragma mark --Private Method
- (NSInteger)currentIndex{
    CGFloat x = self.collectionView.contentOffset.x;
    NSInteger num = x / UIScreenWidth;
    return num + 1;
}
- (void)updateTitle{
    self.title = [NSString stringWithFormat:@"%ld/%ld",[self currentIndex],self.model.goodsorder.count];
}
- (void)goNextGoodComment{
     CGFloat x = self.collectionView.contentOffset.x;
    [self.collectionView setContentOffset:CGPointMake(x + UIScreenWidth, 0) animated:YES];
}
#pragma mark --Action Method
- (void)back{
    if ([self currentIndex] != self.model.goodsorder.count) {
        [self showAlertCancelAndConfirm:@"您还没有商品评价完，放弃会默认好评哟" andWithBlock:^(NSString *name) {
            if ([name isEqualToString:@"确认"]) {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}
- (void)onSelectedGoodWithIndexPath:(NSIndexPath*)indexPath cell:(KLCommentCollectionViewCell*)cell{
    KLOrderGoodModel * model = self.model.goodsorder[indexPath.row];
    KLGoodDetailViewController * vc = [KLGoodDetailViewController new];
    vc.goodID = model.goods_id.description;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)onSelectedCommitWithIndexPath:(NSIndexPath*)indexPath cell:(KLCommentCollectionViewCell*)cell{
      KLOrderGoodModel * model = self.model.goodsorder[indexPath.row];
    if (!cell.textView.text.length) {
        [SVProgressHUD showErrorWithStatus:@"您还没有输入商品评价"];
        return;
    }
    [self sendCommentWithModel:model num:@(cell.xingxingView.chosedNum).description text:cell.textView.text];
}
#pragma mark --NetWork Method
- (void)sendCommentWithModel:(KLOrderGoodModel*)model num:(NSString*)num text:(NSString*)text{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/comment",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    
    if (text.length) {
        [dic setObject:text forKey:@"comment"];
    }
    if (num.length) {
        [dic setObject:num forKey:@"level"];
    }
    [dic setObject:self.model.orderID forKey:@"order_id"];
    [dic setObject:model.goods_id.description forKey:@"goods_id"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSInteger num = [self currentIndex];
                                                 if (num == self.model.goodsorder.count) {
                                                     [SVProgressHUD showSuccessWithStatus:@"所有商品评价成功"];
                                                     [self.navigationController popViewControllerAnimated:YES];
                                                 }else{
                                                     [SVProgressHUD showSuccessWithStatus:@"评价成功"];
                                                     [self goNextGoodComment];
                                                 }
                                               
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
